package world.ztomorrow.common.interceptor;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;
import world.ztomorrow.common.constant.SystemConstant;
import world.ztomorrow.common.utils.UserHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@ConditionalOnClass(DispatcherServlet.class)
public class AuthInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader(SystemConstant.NOVEL_FRONT_KEY);
        if (userId != null){
            UserHolder.setUserId(Long.parseLong(userId));
        }

        String authorId = request.getHeader(SystemConstant.NOVEL_AUTHOR_KEY);
        if (authorId != null) {
            UserHolder.setAuthorId(Long.parseLong(authorId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.clear();
    }
}
